package com.jch.fs.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.text.SimpleDateFormat;
import java.util.Date;

public class FsServerHandler extends ChannelInboundHandlerAdapter {

    static final SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss:SSS");
    static String now(){
        return dateFormat.format(new Date());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(now() + " 客户端：" + ctx.channel().remoteAddress().toString() + " 接入：" + ctx.channel().localAddress().toString());
        ctx.writeAndFlush(now() + " 连接服务器成功。--\r\n");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.err.println(now() + " 客户端：" + ctx.channel().remoteAddress().toString() + " 主动断开连接。");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(now() + " 收到信息：" + msg);
        ctx.writeAndFlush(now() + " " + msg + "\r\n");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println(now() + " 读取：" + ctx.channel().remoteAddress().toString() + " 发送的消息完成。");
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println(now() + " 异常：" + cause.getMessage());
        ctx.close();
    }
}
